import { BrowserWindow, session } from 'electron'
import { readdir, stat } from 'fs/promises'
import path from 'path'
import preload from './preload?url'
import * as server from './server'

export const loadExtension = async () => {
  const extensionsDir = path.resolve('extensions')

  try {
    if ((await stat(extensionsDir)).isDirectory()) {
      const dirs = await readdir(extensionsDir, { withFileTypes: true })
      for (const dir of dirs) {
        if (dir.isDirectory()) {
          try {
            const extensionDir = path.join(extensionsDir, dir.name)
            const extension = await session.defaultSession.loadExtension(
              extensionDir,
              {
                allowFileAccess: true
              }
            )
            const { id, name, version } = extension
            console.info(
              'Load extension success: name=%o id=%o version=%o',
              name,
              id,
              version
            )
          } catch (err) {
            console.error(err)
          }
        }
      }
    }
  } catch {}
}

export const createWindow = async (
  options?: Electron.BrowserWindowConstructorOptions
) => {
  const window = new BrowserWindow({
    ...options,
    show: false,
    webPreferences: {
      ...options?.webPreferences,
      preload
    }
  })

  window.maximize()

  if (__DEV__) {
    window.webContents.openDevTools({ mode: 'right' })
  } else {
    window.setMenu(null)
  }

  return window
}

let mainWindow: BrowserWindow | undefined

export const createMainWindow = async (url?: string) => {
  const window = (mainWindow = await createWindow())

  if (__DEV__) {
    window.once('closed', () => {
      if (window === mainWindow) {
        mainWindow = undefined
      }
    })
  }

  if (!url) {
    const { address, port } = await server.appServer.listen()
    url = `http://${address}:${port}`
  }
  window.loadURL(url)
  window.show()

  return window
}

if (module.hot) {
  module.hot.watch<typeof import('./server')>('./server', (server) => {
    server.appServer.listen().then(({ address, port }) => {
      if (mainWindow) {
        const views = mainWindow.getBrowserViews()
        for (const view of views) {
          view.webContents.reload()
        }
      } else {
        createMainWindow(`http://${address}:${port}`)
      }
    })
  })
  module.hot.on('beforeUnload', () => {
    if (!module.hot.isObsolete()) {
      module.hot.preventReload()
    }
  })
}
